<template>
  <div>
    <el-row type="flex" justify="space-between" :gutter="10">
      <el-col :span="12">
        <el-input v-model="queryForm.username" placeholder="请输入用户账号" style="width: 100%;"></el-input>
      </el-col>
      <el-col :span="12" style="text-align: start;">
        <el-button type="danger" @click="handleSearch">查询</el-button>
        <el-button @click="handleClear">清空</el-button>
      </el-col>
    </el-row>
    <div v-show="userList.length>0" style="width: 100%;margin-top: 10px;">
      <el-table :data="userList" height="250" style="width: 100%;border-radius: 3px;">
        <el-table-column prop="username" label="姓名" width="100">
        </el-table-column>
        <el-table-column label="部门">
          <template slot-scope="scope">
            <div v-for="departName in scope.row.departNames">
              <el-tag v-show="ifAIPMClass(departName)" size="success" type="success">
                {{departName}}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="100" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleShowChangeClassModal(scope.row)">调班</el-button>
            <el-button type="text" size="small" @click="handleChangePasswordModal(scope.row)">改密</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="重置密码" :width="screenWidth>600?'40%':'80%'" :visible.sync="changePasswordDialogVisible" center
      :append-to-body="true">
      <el-form :model="userInfo">
        <el-form-item label="账号" label-width="50px">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="50px">
          <el-input v-model="userInfo.password" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="changePasswordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleChangePassword">重 置</el-button>
      </div>
    </el-dialog>
    <el-dialog title="调整班级" :width="screenWidth>600?'40%':'80%'" :visible.sync="changeClassDialogVisible" center
      :append-to-body="true">
      <el-form :model="userInfo">
        <el-form-item label="账号" label-width="50px">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="班级" label-width="50px">
          <el-input v-model="userInfo.aipmClassName" disabled></el-input>
        </el-form-item>
        <el-form-item label="调整" label-width="50px">
          <el-select v-model="selectedAipmClassId" placeholder="请选择班级" style="width: 100%;" filterable>
            <el-option v-for="item in allDepartList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="changeClassDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleChangeClass">调 班</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { ajaxGetDictItems } from '@/api/system'
  import { getUserList, getUserDepartList, editUser, changePassword } from '@/api/user'
  import { getDeptListByName } from '@/api/dept'
  export default {
    data() {
      return {
        screenWidth: document.documentElement.clientWidth,
        changeClassDialogVisible: false,
        changePasswordDialogVisible: false,
        loading: false,
        queryForm: { username: "" },
        userList: [],
        userInfo: {},
        userDepartList: [],
        allDepartList: [],
        selectedAipmClassId: ''
      }
    },
    beforeDestroy() {
      document.onkeydown = null
    },
    created() {
      var that = this
      document.onkeydown = function (e) {
        var key = window.event.keyCode
        if (key == 13) {
          that.handleSearch()
        }
      }
      this.queryDeptListByName(`AI产品经理%期（V%）`)
    },
    methods: {
      handleClear() {
        this.queryForm = {}
        this.userList = []
      },
      ifAIPMClass(className) {
        return className.indexOf('AI产品经理') > -1 && className.indexOf('录播预习') == -1
      },
      handleSearch() {
        let that = this
        if (!this.queryForm.username || this.queryForm.username == '') {
          this.$message.warning('请输入账号查询')
          return
        }
        that.loading = true
        getUserList({
          username: `*${that.queryForm.username}*`,
          column: 'createTime',
          'order': 'desc',
          'pageNo': 1,
          'pageSize': 20
        }).then((res) => {
          if (res.result && res.result.records && res.result.records.length > 0) {
            that.userList = res.result.records
          } else {
            that.$message.warning('未查到数据')
          }
        }).catch(err => {
          that.$message.error(err.message)
        }).finally(() => {
          that.loading = false
        })
      },
      queryDeptListByName(deptName) {
        getDeptListByName({ deptName }).then((res) => {
          this.allDepartList = res.result.map((item) => {
            return {
              value: item.id,
              label: item.departName
            }
          })
        })
      },
      handleShowChangeClassModal(user) {
        let that = this
        that.userInfo = { id: user.id, username: user.username }
        getUserDepartList({
          userId: user.id
        }).then((res) => {
          that.userDepartList = res.result;
          const aipmClass = res.result.find((item) => {
            return that.ifAIPMClass(item.title)
          })
          that.userInfo.aipmClassName = aipmClass && aipmClass.title
          that.userInfo.aipmClassId = aipmClass && aipmClass.value
          that.selectedAipmClassId = aipmClass && aipmClass.value
          that.changeClassDialogVisible = true
        })
      },
      handleChangeClass() {
        if (this.userInfo.aipmClassId == this.selectedAipmClassId) {
          this.$message.warning('无需调整')
          return
        }
        this.$confirm('确定要调整班级吗 ?', '调整班级', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            const userDepartIds = [this.selectedAipmClassId]
            this.userDepartList.forEach(item => {
              if (!this.ifAIPMClass(item.title)) userDepartIds.push(item.value)
            });
            editUser({
              id: this.userInfo.id,
              selecteddeparts: userDepartIds.join(',')
            }).then((res) => {
              if (res.success)
                this.$message.success(res.message)
              else
                this.$message.error(res.message)
              this.changeClassDialogVisible = false
              this.handleSearch()
            })
          })
      },
      handleChangePasswordModal(user) {
        this.userInfo = { id: user.id, username: user.username, password: Math.random().toString(36).slice(-8) }
        this.changePasswordDialogVisible = true
      },
      handleChangePassword() {
        this.$confirm('确定要重置密码吗 ?', '重置密码', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            const userInfo = this.userInfo
            changePassword({
              username: userInfo.username,
              password: userInfo.password,
              confirmpassword: userInfo.password,
            }).then((res) => {
              this.changePasswordDialogVisible = false
              const message = `你好，学习平台账号【${userInfo.username}】密码已重置为【${userInfo.password}】, 请登录平台确认!`
              if (res.success)
                this.$alert(message, '密码重置成功', {
                  center: true,
                  type: 'success',
                  confirmButtonText: '复制信息',
                }).then(() => {
                  this.$copyText(message).then(() => {
                    this.$message.success('复制成功')
                  })
                })
              else
                this.$message.error(res.message)

            })
          })

      }
    }
  }
</script>